package JasPerl::JSTL::Fmt::MessageTag;

use 5.010;
use strict;
use warnings;

use parent qw(JasPerl::TagExt::JspBodyTag);

use JasPerl::JSTL::Core::Config qw(:fmt);
use JasPerl::JSTL::Fmt::LocalizationContext;

my $BUNDLE_CLASS = 'JasPerl::JSTL::Fmt::BundleTag';

sub set_bundle {
    $_[0]->{bundle} = $_[1];
}

sub set_key {
    $_[0]->{key} = $_[1];
}

sub set_scope {
    $_[0]->{scope} = JasPerl::PageContext->get_scope_by_name($_[1]);
}

sub set_var {
    $_[0]->{var} = $_[1];
}

sub add_parameter {
    push @{$_[0]->{params}}, $_[1];
}

sub get_bundle {
    my $self = shift;
    my $pc = $self->get_jsp_context();
    if (my $parent = $self->find_ancestor_isa($BUNDLE_CLASS)) {
        return $parent->get_bundle();
    } else {
        return JasPerl::JSTL::Fmt::LocalizationContext->get_bundle($pc);
    }
}

sub do_tag {
    my $self = shift;
    my $context = $self->get_jsp_context();
    my $content = $self->get_body_content();
    my $key = $self->{key} // $content;
    warn "--- key='$key'";
    my $message;
    if (my $parent = $self->find_ancestor_isa($BUNDLE_CLASS)) {
        my $bundle = $parent->get_bundle();
        my $prefix = $parent->get_prefix() // '';
        $message = $bundle->get_message($prefix . $key, $self->{params});
    } else {
        my $bundle = JasPerl::JSTL::Fmt::LocalizationContext->get_bundle($context);
        $message = $bundle->get_message($key, $self->{params});
    }

    if (defined $self->{var}) {
        $context->set_attribute($self->{var}, $message, $self->{scope});
    } else {
        $context->get_out()->print($message);
    }
}

1;
